package com.moon.interview.filter;

import com.moon.interview.utils.BlankIpUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;

import java.io.IOException;

/**
 * 黑名单过滤器
 *
 * @author MoonX
 * @date 2023/3/28 14:06
 */
@WebFilter(urlPatterns = "/*", filterName = "blankIpFilter")
public class BlankIpFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取客户端ip
        String ipAddr = servletRequest.getRemoteAddr();
        // 判断是否为黑名单ip
        if (BlankIpUtils.isBlankIp(ipAddr)) {
            servletResponse.setContentType("text/json;charset=UTF-8");
            servletResponse.getWriter().write("{\"errorCode\":-1,\"msg\":\"黑名单ip，禁止访问\"}");
            return;
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
